package com.zbs.framework.dao.rolefunction.repository;

import com.zbs.framework.dao.function.entity.Function;
import com.zbs.framework.dao.permission.entity.Permission;
import com.zbs.framework.dao.userfunction.entity.UserFunction;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface UserFunctionRepository extends JpaRepository<UserFunction, Long> {

    @Query("select p from FunctionPermission fp" +
            " left join Permission p on fp.permissionId = p.id" +
            " inner join UserFunction uf on fp.functionId = uf.functionId where uf.userId = :userId")
    List<Permission> findPermissions(@Param("userId") Long userId);

    @Query("select uf.functionId from UserFunction uf where uf.userId = :userId")
    List<Long> findFunctionIds(@Param("userId") Long userId);

    @Query("select f from UserFunction uf left join Function f on uf.functionId = f.id" +
            " where uf.userId = :userId")
    List<Function> findFunctions(@Param("userId") Long userId);

    @Query(value = "SELECT COUNT(*) FROM mnt_user_function uf LEFT JOIN mnt_function f on f.id = uf.function_id WHERE uf.user_id = :userId AND f.identifier = :identifier limit 1",nativeQuery = true)
    Integer existsFunctionsByIdentifier(@Param("userId") Long userId,@Param("identifier") String identifier);

    void deleteByUserIdAndFunctionId(Long userId, Long functionId);

    void deleteAllByUserId(Long userId);
}
